//
//  YBVideoPlayerVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/30.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "YBVideoPlayerVC.h"
#import "YBApiManager+Global.h"
#import "CacheHelper.h"
#import <LKDBHelper/LKDBHelper.h>

@implementation YBVideoPlayerVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = nil;
    if (self.msg.filePath.isHaveStr == YES) {
        url = self.msg.allFilePath.fileToURL;
    } else {
        url = self.msg.content.toURL;
        [self downloadVideo];
    }
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    self.player = [AVPlayer playerWithPlayerItem:item];
    self.delegate = self;
    [self.player play];
    
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(saveVideoToSystemPhotoAlbum:)];
    [self.view addGestureRecognizer:longPressGR];
    
}
- (void)saveVideoToSystemPhotoAlbum:(UILongPressGestureRecognizer *)gr {
    
    if (gr.state == UIGestureRecognizerStateBegan) {
        
        [LBXAlertAction showActionSheetWithTitle:@"视频选项" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:@[@"保存至相册"] chooseBlock:^(NSInteger buttonIdx) {
            if (buttonIdx == 1) {
                if (self.msg.filePath.isHaveStr == NO) {
                    [MBProgressHUD showTipMessageInView:@"视频还未下载完成，稍后再试" timer:1.0f];
                } else {
                    NSString *videoPath = self.msg.allFilePath;
                    BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath);
                    
                    if(compatible) { UISaveVideoAtPathToSavedPhotosAlbum(videoPath,self,@selector(savedVideoPhotoImage:didFinishSavingWithError:contextInfo:),nil);
                    }
                }
            }
        }];
    }
}
- (void)savedVideoPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError*)error contextInfo: (void*)contextInfo {
    
    if(error) {
        [MBProgressHUD showTipMessageInView:[NSString stringWithFormat:@"保存视频失败: %@", error.localizedDescription] timer:1.0f];
    } else {
        [MBProgressHUD showTipMessageInView:@"视频保存成功" timer:1.0f];
    }
    
}
- (void)downloadVideo {
    
    [[YBApiManager.shareManager downloadTask:self.msg.content] subscribeNext:^(id  _Nullable x) {
        if ([x isKindOfClass:NSNumber.class] == YES) {
            return;
        }
        NSURL *fileURL = x;
        NSData *data = [NSData dataWithContentsOfURL:fileURL];
        NSLog(@"download file path = %@", fileURL);
        [[CacheHelper helper] cacheFileWitType:self.msg.type fileData:data completion:^(NSString * _Nonnull filePath) {
            self.msg.filePath = filePath;
            [self.msg updateToDB];
            [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
        }];
        
    } error:^(NSError * _Nullable error) {
        NSLog(@"download error = %@", error);
    }];
}

- (void)playerViewControllerWillStartPictureInPicture:(AVPlayerViewController *)playerViewController {
    NSLog(@"\n%s [Line %d]", __PRETTY_FUNCTION__, __LINE__);
}
- (void)playerViewControllerDidStartPictureInPicture:(AVPlayerViewController *)playerViewController {
    NSLog(@"\n%s [Line %d]", __PRETTY_FUNCTION__, __LINE__);
}
- (void)playerViewController:(AVPlayerViewController *)playerViewController failedToStartPictureInPictureWithError:(NSError *)error {
    NSLog(@"\n%s [Line %d]", __PRETTY_FUNCTION__, __LINE__);
    
}

@end
